import { EChartsOption } from 'echarts'

declare interface chartsData {
  [T: string]: Array<number> | number
}

declare interface expandObject {
  smooth?: boolean
  options?: chartsData
  legend?: any
}

export function deepMerge(...objs: any[]): any {
  const result = Object.create(null)
  objs.forEach(obj => {
    if (obj) {
      Object.keys(obj).forEach(key => {
        const val = obj[key]
        if (isPlainObject(val)) {
          // 递归
          if (isPlainObject(result[key])) {
            result[key] = deepMerge(result[key], val)
          } else {
            result[key] = deepMerge(val)
          }
        } else {
          result[key] = val
        }
      })
    }
  })
  return result
}

export function isPlainObject(val: unknown): boolean {
  return toString.call(val) === '[object Object]'
}

export function buildOptionFromEcharts(echarts: chartsData, type: string, expand?: expandObject): EChartsOption {
  const options = expand && expand.options ? deepMerge(expand.options) : {}
  if (options.series) {
    delete options.series
  }
  if (options.legend) {
    delete options.legend
  }
  if (!options.title) {
    options.title = {}
  }
  options.series = []
  options.legend = {}
  options.legend.data = []
  if (type === 'line') {
    const smooth = expand && expand.smooth ? expand.smooth : false
    Object.keys(echarts).forEach(key => {
      options.series.push({
        name: key,
        data: echarts[key],
        type: 'line',
        smooth
      })
      options.legend.data.push(key)
    })
    if (!options.yAxis) {
      options.yAxis = {}
    }
  } else if (type === 'bar') {
    Object.keys(echarts).forEach(key => {
      options.series.push({ name: key, data: echarts[key], type: 'bar' })
      options.legend.data.push(key)
    })
    if (!options.yAxis) {
      options.yAxis = {}
    }
  } else if (type === 'pie') {
    const pieData: { name: string; value: any }[] = []
    Object.keys(echarts).forEach(key => {
      pieData.push({ name: key, value: echarts[key] })
      options.legend.data.push(key)
    })
    options.series.push({ type: 'pie', data: pieData })
    if (expand && expand.legend) {
      Object.keys(expand.legend).forEach(key => {
        options.legend[key] = expand.legend[key]
      })
    }
  }
  return options
}
